<template>
    <div>
        <section>
            <input v-model="keyWord" type="text" placeholder="输入城市名或拼音" />
        </section>
        <div class="search-content" ref="search" v-show="keyWord">
            <ul>
                <li class="search-item border-bottom" v-show="lists.length" v-for="item in lists" :key="item.id" @click="cityClick(item.name)">{{item.name}}</li>
                <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
            </ul>
        </div>
    </div>
</template>

<script>
import { mapMutations } from "vuex";
import Bscroll from "better-scroll";
export default {
  name: "CitySearch",
  props: {
    list: Object
  },
  data() {
    return {
      keyWord: "",
      lists: [],
      timer: null,
      scroll: []
    };
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search);
  },
  computed: {
    hasNoData() {
      return !this.lists.length;
    }
  },
  watch: {
    keyWord() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyWord) {
        this.lists = [];
        return false;
      }
      this.timer = setTimeout(() => {
        let result = [];
        for (let i in this.list) {
          this.list[i].forEach(item => {
            if (
              item.spell.indexOf(this.keyWord) > -1 ||
              item.name.indexOf(this.keyWord) > -1
            ) {
              result.push(item);
            }
          });
        }
        this.lists = result;
      }, 100);
    }
  },
  methods: {
    cityClick(city) {
      this.changeCity(city);
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"])
  }
};
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';

section {
    padding: 0 0.2rem;
    line-height: 0.82rem;
    background: $bgColor;

    input {
        width: 100%;
        line-height: 0.62rem;
        height: 0.62rem;
        text-align: center;
        border-radius: 0.06rem;
        color: #666;
        padding: 0 0.1rem;
        box-sizing: border-box;
    }
}

.search-content {
    position: absolute;
    top: 1.68rem;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: 1;
    background: #eee;
}

.search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #ffffff;
    color: #666;
}
</style>